const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const cors = require('koa2-cors');
const path = require('path');
const log4 = require('koa-log4');
const fs = require('fs');

const log = require('./config/log/log');
const index = require('./routes/index');
const users = require('./routes/users');

// error handler
onerror(app)


// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(log())
// app.use(cors())
app.use(json())
// app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'hbs',
  map: { hbs: 'handlebars' }
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  ctx.logger.all(ctx)
  await next();
  try {
    let ms = new Date() - start;
    // 进入下一中间件
    if (ctx.response.stuats === 404) {
      ctx.response.throw(404);
    }
    ctx.logger.reply(ctx, ms);
  } catch (e) {
    let ms = new Date() - start;
    ctx.logger.err(ctx, e, ms)
  }

  // console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
